package com.zjitc.controller;

import com.zjitc.model.Country;
import com.zjitc.service.CountryService;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.InternalResourceView;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/3/20 16:12
 * @description:
 */
@Controller
public class UserController {
  @Autowired
  private CountryService countryService;

  @RequestMapping("/findAll")
  public ModelAndView findAll(){
    List<Country> list = countryService.findAll();

    ModelAndView mv = new ModelAndView();
    mv.addObject("country", list);
    mv.setViewName("/WEB-INF/views/countries.jsp");

    return mv;
  }

  @RequestMapping("/add")
  public ModelAndView add(Country country){

    ModelAndView mv = new ModelAndView();
    int add = countryService.add(country);
    mv.addObject("add", add);
    mv.setView(new InternalResourceView("/app/findAll"));
    return mv;
  }

  @RequestMapping("/delete")
  public View delete(HttpServletRequest request, HttpServletResponse response){
    String code = request.getParameter("code");
    String  count = countryService.delete(code);
    View view = new InternalResourceView("/app/findAll");

    return view;
  }

  @RequestMapping("/findByCode")
  public ModelAndView findByCode(HttpServletRequest request){

    String code = request.getParameter("code");

    Country country = countryService.findByCode(code);

    ModelAndView mv = new ModelAndView();

    mv.addObject("list", country);

    mv.setView(new InternalResourceView("/update.jsp"));

    return mv;
  }
  @RequestMapping("/showByCode")
  public ModelAndView showByCode(HttpServletRequest request){
    String code = request.getParameter("code");
    Country country = countryService.showByCode(code);
    ModelAndView mv=new ModelAndView();
    mv.addObject("country",country);
    mv.setView(new InternalResourceView("/app/findAll"));
    return mv;
  }

  @RequestMapping("/update")
  public ModelAndView update(Country country){
    ModelAndView mv = new ModelAndView();
    int update = countryService.update(country);
    mv.addObject("update",update);
    mv.setView(new InternalResourceView("/app/findAll"));
    return mv;
  }

}